﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace mcmdFinder
{

    public partial class mcmdFinder : Form
    {

        private string envName = string.Empty;

        private string DAT_FILE = ".\\env.dat";

        private const string SEARCH_TYPE_CMD_NAME = "CMD";
        private const string SEARCH_TYPE_FILE_NAME = "FILE";

        

        public mcmdFinder()
        {
            InitializeComponent();
            parseDatFile();
        }

        

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("testsss");
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }


        /// <summary>
        /// Prase the env information
        /// Get the dir defined in environment
        /// </summary>
        private bool parseEnvName()
        {
            this.envName = this.textBoxEnvName.Text;

            if(string.IsNullOrEmpty(envName))
            {
                MessageBox.Show("No Env Name was found!!!");
                return false;
            }

            // Get Env Info using rpset

            Process process = new Process();
            process.StartInfo.FileName = "rpset.cmd ";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;

            // ">" is used to redirect the output to the file
            process.StartInfo.Arguments = envName + " >" + DAT_FILE ;
            process.Start();
            process.WaitForExit(3000);
            process.Close();
            //process.Kill();

            return true;
        }

        /// <summary>
        /// Parse dat file to get environment information.
        /// </summary>
        private void parseDatFile()
        {
            StreamReader sr = null;
            try
            {
                sr = File.OpenText(DAT_FILE);
                string line = string.Empty;
                line = sr.ReadLine();

                while (line != null)
                {
                    //Console.WriteLine("XXXX: " + line);

                    if (line.Trim().StartsWith("LES:"))
                    {
                        string tempLine = line.Trim().Substring(4);
                        this.textBoxLESDir.Text = tempLine.Trim();
                    }
                    else if (line.Trim().StartsWith("TM:"))
                    {
                        string tempLine = line.Trim().Substring(3);
                        this.textBoxTMDir.Text = tempLine.Trim();
                    }
                    else if (line.Trim().StartsWith("Integrator:"))
                    {
                        string tempLine = line.Trim().Substring(11);
                        this.textBoxSLDir.Text = tempLine.Trim();
                    }
                    else if (line.Trim().StartsWith("SAL:"))
                    {
                        string tempLine = line.Trim().Substring(4);
                        this.textBoxSALDir.Text = tempLine.Trim();
                    }

                    else if (line.Trim().StartsWith("MCS:"))
                    {
                        string tempLine = line.Trim().Substring(4);
                        this.textBoxMCSDir.Text = tempLine.Trim();
                    }
                    else if (line.Trim().StartsWith("MOCA:"))
                    {
                        string tempLine = line.Trim().Substring(5);
                        this.textBoxMOCADir.Text = tempLine.Trim();
                    }

                    line = sr.ReadLine();
                }
            }
            catch (Exception)
            {
                return;
            }
            finally
            {
                if(sr != null)
                {
                    sr.Close();
                }
            }
            
            
        }

        
        private void btnParseEnv_Click(object sender, EventArgs e)
        {
            this.btnParseEnv.Enabled = false;
            this.parseEnvName();
            this.parseDatFile();
            this.btnParseEnv.Enabled = true;
        }

        /// <summary>
        /// Search Key Word
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            if(checkRequiredFields())
            {
                // Clear the original result
                this.dataGridViewResult.Rows.Clear();

                // Get sub folder info
                string subFolder = string.Empty;
                if(this.radioButtonCmdsrcFolder.Checked)
                {
                    subFolder = this.textBoxSubFolderCmdsrc.Text;
                }
                else
                {
                    subFolder = this.textBoxSubFolderSpecific.Text;
                }

                // Parse product directory information
                string lesDir = this.textBoxLESDir.Text + subFolder;
                string tmDir = this.textBoxTMDir.Text + subFolder;
                string slDir = this.textBoxSLDir.Text + subFolder;
                string salDir = this.textBoxSALDir.Text + subFolder;
                string mcsDir = this.textBoxMCSDir.Text + subFolder;
                string mocaDir = this.textBoxMOCADir.Text + subFolder;

                string keyWord = this.textBoxKeyWords.Text;

                // Search by file name
                if (this.checkBoxSearchByFileName.Checked)
                {
                    // Search in LES folder
                    if (this.checkBoxLES.Checked)
                    {
                        DirectoryInfo dirss = new DirectoryInfo(lesDir);
                        findFilesByFileName(dirss, keyWord);
                    }
                    // Search in TM folder
                    if (this.checkBoxTM.Checked)
                    {
                        findFilesByFileName(new DirectoryInfo(tmDir), keyWord);
                    }
                    // Search in SL folder
                    if (this.checkBoxSL.Checked)
                    {
                        findFilesByFileName(new DirectoryInfo(slDir), keyWord);
                    }
                    // Search in SAL folder
                    if (this.checkBoxSAL.Checked)
                    {
                        findFilesByFileName(new DirectoryInfo(salDir), keyWord);
                    }
                    // Search in MCS folder
                    if (this.checkBoxMCS.Checked)
                    {
                        findFilesByFileName(new DirectoryInfo(mcsDir), keyWord);
                    }
                    // Search in MOCA folder
                    if (this.checkBoxMOCA.Checked)
                    {
                        findFilesByFileName(new DirectoryInfo(mocaDir), keyWord);
                    }
                }

                // Search by command name
                if (this.checkBoxSearchByCMDName.Checked)
                {
                    // Search in LES folder
                    if (this.checkBoxLES.Checked)
                    {
                        DirectoryInfo dirss = new DirectoryInfo(lesDir);
                        findFilesByCommandName(dirss, keyWord);
                    }
                    // Search in TM folder
                    if (this.checkBoxTM.Checked)
                    {
                        findFilesByCommandName(new DirectoryInfo(tmDir), keyWord);
                    }
                    // Search in SL folder
                    if (this.checkBoxSL.Checked)
                    {
                        findFilesByCommandName(new DirectoryInfo(slDir), keyWord);
                    }
                    // Search in SAL folder
                    if (this.checkBoxSAL.Checked)
                    {
                        findFilesByCommandName(new DirectoryInfo(salDir), keyWord);
                    }
                    // Search in MCS folder
                    if (this.checkBoxMCS.Checked)
                    {
                        findFilesByCommandName(new DirectoryInfo(mcsDir), keyWord);
                    }
                    // Search in MOCA folder
                    if (this.checkBoxMOCA.Checked)
                    {
                        findFilesByCommandName(new DirectoryInfo(mocaDir), keyWord);
                    }
                }
                
            }

            MessageBox.Show("Search Finished!!!");

        }

        private bool checkRequiredFields()
        {
            if(string.IsNullOrEmpty(this.textBoxLESDir.Text.Trim())
                || string.IsNullOrEmpty(this.textBoxTMDir.Text.Trim())
                || string.IsNullOrEmpty(this.textBoxSLDir.Text.Trim())
                || string.IsNullOrEmpty(this.textBoxSALDir.Text.Trim())
                || string.IsNullOrEmpty(this.textBoxMCSDir.Text.Trim())
                || string.IsNullOrEmpty(this.textBoxMOCADir.Text.Trim()))
            {
                MessageBox.Show("One of the product folders are empty!!");
                return false;
            }

            if(string.IsNullOrEmpty(this.textBoxKeyWords.Text.Trim()))
            {
                MessageBox.Show("Please input a key word!!");
                return false;
            }

            return true;
        }

        /// <summary>
        /// Find files by command name
        /// Note that we don't support wild cards for command name
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="fileFilter"></param>
        private void findFilesByCommandName(DirectoryInfo dir, string fileFilter)
        {
            foreach (DirectoryInfo subDir in dir.GetDirectories())
            {
                // If we search by command name, we should only check mcmd files
                FileInfo[] files = subDir.GetFiles("*.mcmd");
                foreach (FileInfo file in files)
                {
                    using (StreamReader sr = File.OpenText(file.FullName))
                    {
                        string line;
                        line = sr.ReadLine();
                        while (line != null)
                        {
                            if (line.Trim().StartsWith("<name>"))
                            {
                                string tempLine = line.Trim().Substring(6);
                                if (tempLine.StartsWith(fileFilter))
                                {
                                    //this.richTextBoxTestResult.AppendText(file.FullName + "\n");
                                    addToResult(dir, file, fileFilter, SEARCH_TYPE_CMD_NAME);
                                    break;
                                }
                            }

                            line = sr.ReadLine();
                        }
                    }

                }
            }
        }

        /// <summary>
        /// Find files by file name
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="fileFilter"></param>
        private void findFilesByFileName(DirectoryInfo dir, string fileFilter)
        {
            // Search in this directory(not contains sub directories)
            FileInfo[] files = dir.GetFiles(fileFilter);
            foreach (FileInfo file in files)
            {
                //this.richTextBoxTestResult.AppendText(file.FullName + "\n");
                addToResult(dir, file, fileFilter, SEARCH_TYPE_FILE_NAME);
            }
            
            // Search in all the sub directories
            foreach (DirectoryInfo subDir in dir.GetDirectories())
            {
                findFilesByFileName(subDir, fileFilter);
            }
        }

        private void radioButtonCustomeFolder_CheckedChanged(object sender, EventArgs e)
        {
            this.textBoxSubFolderSpecific.Enabled = true;
        }

        private void radioButtonCmdsrcFolder_CheckedChanged(object sender, EventArgs e)
        {
            this.textBoxSubFolderSpecific.Enabled = false;
        }

        /// <summary>
        /// Add the search result to the data grid view
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="file"></param>
        /// <param name="fileFilter"></param>
        /// <param name="searchType"></param>
        private void addToResult(DirectoryInfo dir,FileInfo file,string fileFilter,string searchType)
        {
            string product = getProductFromDir(dir.FullName);

            string command = string.Empty;
            if(SEARCH_TYPE_CMD_NAME.Equals(searchType))
            {
                command = fileFilter;
            }

            string fileName = file.ToString();

            string fullPath = file.FullName;

            this.dataGridViewResult.Rows.Add(new Object[] {product, command, fileName, fullPath});
        }

        private string getProductFromDir(string dir)
        {
            if(dir.Contains(this.textBoxLESDir.Text))
            {
                return "LES";
            }
            if (dir.Contains(this.textBoxTMDir.Text))
            {
                return "TM";
            }
            if (dir.Contains(this.textBoxSLDir.Text))
            {
                return "SL";
            }
            if (dir.Contains(this.textBoxSALDir.Text))
            {
                return "SAL";
            }
            if (dir.Contains(this.textBoxMCSDir.Text))
            {
                return "MCS";
            }
            if (dir.Contains(this.textBoxMOCADir.Text))
            {
                return "MOCA";
            }
            return "";
        }


        /// <summary>
        /// Open selected file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridViewResult.SelectedRows)
            {
                string fileName = row.Cells[3].Value as string;

                Process process = new Process();
                process.StartInfo.FileName = fileName;
                process.Start();
                process.Close();
            }

        }

        /// <summary>
        /// Open select file's folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridViewResult.SelectedRows)
            {
                string fileName = row.Cells[3].Value as string;

                FileInfo file = new FileInfo(fileName);
                string folderName = file.Directory.FullName;

                Process process = new Process();
                process.StartInfo.FileName = folderName;
                process.Start();
                process.Close();
            }
        }

       


    }
}
